package cn.signalpha.modules.shop.controller.api;

import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.common.constant.MsgConstant;
import cn.signalpha.common.dto.IdDTO;
import cn.signalpha.common.utils.Assert;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.secure.TokenUser;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.modules.shop.entity.UserAddress;
import cn.signalpha.modules.shop.service.UserAddressService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * 用户收货地址
 *
 * @author suguangjun
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SHOP_NAME + "/wap/user/address")
@Api(value = "收货地址", tags = "收货地址")
public class ApiUserAddressController extends BaseController {

    private final UserAddressService userAddressService;

    @GetMapping("/list")
	@ApiOperation(value = "列表", notes = "")
    public R<List<UserAddress>> list(TokenUser tokenUser){
		List<UserAddress> list = userAddressService.list(Wrappers.<UserAddress>lambdaQuery()
			.eq(UserAddress::getUserId, tokenUser.getUserId())
			.orderByDesc(UserAddress::getIsDefault).orderByDesc(UserAddress::getId)
		);
        return R.data(list);
    }

    @GetMapping("/info")
	@ApiOperation(value = "详情", notes = "传入id")
    public R<UserAddress> info(@RequestParam Long id){
        return R.data(userAddressService.getById(id));
    }

    @PostMapping("/submit")
    @ApiOperation("新增或修改")
    public R save(@Valid @RequestBody UserAddress userAddress){
		Long userId = getUser().getUserId();
		if(userAddress.getIsDefault() == 1){
			userAddressService.cleanUserDefaultAddress(userId);
		}else{
			//第一个地址作为默认地址
			if(userAddressService.count(Wrappers.<UserAddress>lambdaQuery().eq(UserAddress::getUserId, userId)) == 0){
				userAddress.setIsDefault(1);
			}
		}
        userAddress.setUserId(userId);
        return R.status(userAddressService.saveOrUpdate(userAddress));
    }

	@PostMapping("/set")
	@ApiOperation("设为默认地址")
	public R set(@Valid @RequestBody IdDTO idDTO){
		UserAddress userAddress = userAddressService.getById(idDTO.getId());
		Assert.isNull(userAddress, MsgConstant.OBJECT_NULL);
		userAddressService.cleanUserDefaultAddress(getUser().getUserId());
		return R.status(userAddressService.updateById(UserAddress.builder().id(userAddress.getId()).isDefault(1).build()));
	}

    @PostMapping("/remove")
    @ApiOperation(value = "删除", notes = "传入id即可")
    public R delete(@RequestBody UserAddress userAddress){
        return R.status(userAddressService.removeById(userAddress.getId()));
    }

}
